package org.csu.mypetstorecmsapi.controller;

import org.csu.mypetstorecmsapi.common.BaseResponse;
import org.csu.mypetstorecmsapi.domain.User;
import org.csu.mypetstorecmsapi.persistence.UserDao;
import org.csu.mypetstorecmsapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/users")
public class UserController
{
    @Autowired
    UserService userService;

    //获取user信息列表
    @GetMapping
    public BaseResponse<List<User>> getUsers()
    {
        return BaseResponse.createForSuccess(userService.getUsers());
    }

    //获取某一user信息
    @GetMapping("/{id}")
    public BaseResponse<User> getUser(@PathVariable int id)
    {
        return BaseResponse.createForSuccess(userService.getUserById(id));
    }

    //新增
    @PostMapping
    public BaseResponse<Void> addUser(@RequestBody User user)
    {
        if(!userService.existByUsername(user.getUsername())) {
            userService.addUser(user);
            return BaseResponse.createForSuccess();
        }

        else return BaseResponse.createForError("该用户名已存在");
    }

    //删除
    @DeleteMapping("/{id}")
    public BaseResponse<Void> deleteUser(@PathVariable int id)
    {
        userService.deleteUser(id);
        return BaseResponse.createForSuccess();
    }

    //修改user信息
    @PutMapping("/{id}")
    public BaseResponse<Void> editUser(@PathVariable int id, @RequestBody User user)
    {
        User u = userService.getUserById(id);
        if(Objects.equals(u.getUsername(), user.getUsername()) || !userService.existByUsername(user.getUsername())) {
            {
                userService.editUser(id, user);
                return BaseResponse.createForSuccess();
            }
        }
        return BaseResponse.createForError("该用户名已存在");
    }
}
